from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from myadmin import models

#引入绘图模块
from PIL import Image, ImageDraw, ImageFont
#引入随机函数模块
import random

# 商品　首页
def index(request):


    # data 里的样式 不包括上面的data
    '''
    [
        {一级[0],
            [
                {一级子1},
                {一级子2},
                {一级子3},
                {一级子4}
                ....
            ]
        },
        {一级[1],er:[...................]},
    ]
    '''
    # 获取一级
    data = models.Types.objects.filter(pid=0)
    #  yi = [{一级[0]},{一级[1]},{一级[2]}]
    # 获取二级  放入字典
    for i in data:
        i.er = models.Types.objects.filter(pid=i.id)

    chuan = {'info':data}


    return render(request,'home/index.html',chuan)

# 商品　列表页
def goodslist(request,yid):

    yid = int(yid)
    print(yid,type(yid))
    # 获取 选择的对象
    os = models.Types.objects.get(id=yid)

    # 判断是不是一级分类
    if os.pid == 0:
        # 获取 点击的父分类.子分类.对应的全部商品  
        ju = models.Types.objects.get(id=yid)
        # 获取当前对象的 二级分类
        ju.erlist = models.Types.objects.filter(pid=ju.id)

        ju.goodslist = []
        # 将对应的商品添加到  ju
        for x in ju.erlist:
            ju.goodslist += models.Goods.objects.filter(tid=x.id)           
        '''
         当前ju  [
                    {
                        {一级分类object},

                        erlist: [ 
                                    {'二级分类object 1' },
                                    {'二级分类object 2' },
                                 ]
                        goodslist:[  {1类商品1},{1类商品2},{1类商品3},{1类商品4}.....{2类商品1},{2类商品2},{2类商品3},{2类商品4}.....   ]
                    }
                  ]
        '''   
    else:
        # 魅族手机点进来
        # os 是二级分类

        # 先找对应的一级分类
        ju = models.Types.objects.get(id=os.pid)
        # 获取 一级分类下的 全部二级分类
        ju.erlist = models.Types.objects.filter(pid=ju.id)

        # 获取 改二级分类下的全部商品
        ju.goodslist = models.Goods.objects.filter(tid=os.id)

  
    data = {'info':ju,'lei':os}
    return render(request,'home/list.html',data)
    
# 商品　详情页
def onegoods(request,gid):

    goods = models.Goods.objects.get(id=gid)
    chaun = {'info':goods}

    return render(request,'home/one.html',chaun)

# 登录
def login(request):
    nextpath = request.GET.get('nextpath','/')
    # 判断请求方式
    if request.method == 'POST':
        # 获取页面信息        
        jie = request.POST.dict()
        jie.pop('csrfmiddlewaretoken')
               
        # 判断 验证码是否正确  
        if jie['vcode'].upper() != request.session['verifycode'].upper(): 
            return HttpResponse('<script>alert("验证码错误,请从新登陆");location.href="/login/"</script>')            
        try:
            # 获取数据库信息
            # ku = models.Users.objects.get(phone=jie['phone'],None)
            ku = models.Users.objects.get(phone=request.POST['phone'])
            if ku.password == request.POST['password']:                
                # 将该用户数据存入 页面请求
                request.session['VipUser'] = {'uid':ku.id,'username':ku.username,'phone':ku.phone,'status':ku.state}
                return HttpResponse('<script>alert("登陆成功");location.href="/"</script>')
            else:
                return HttpResponse('<script>alert("手机号或密码错误,请从新登陆");location.href="/login/"</script>')
        except Exception as e:
            return HttpResponse('<script>alert("手机号或密码错误,请从新登陆");location.href="/login/"</script>')    
    else:
        return render(request,'home/login.html')

# 退出登陆
def logout(request):
    # 删除页面记录的 *session* 请求  
    del request.session['VipUser']
    return HttpResponse('<script>alert("退出登录成功");location.href="/"</script>')    

# 注册
def register(request):
    # 判断请求方式
    if request.method == 'POST':
        try:
            re = request.POST.dict()
            re.pop('csrfmiddlewaretoken')

            # 验证手机验证码是否正确
            if request.session['msgcode'] != re['msgcode']:
                return HttpResponse('<script>alert("手机验证码错误");location.href="/register/"</script>')
            # 删除数据中的msgcode
            re.pop('msgcode')

            # 密码加密
            password = make_password(re['password'], None, 'pbkdf2_sha256')
            re['pic'] = "/static/pics/"+"user.jpg"
            models.Users.objects.create(**re)
            return HttpResponse('<script>alert("注册成功,请登录");location.href="/login/"</script>')
        except Exception as e:
            return HttpResponse('<script>alert("注册失败");location.href="/register/"</script>')
    else:
        return render(request,'home/register.html')
        
# 验证码
def verifycode(request):
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

# 短信认证
def sendmsg(request):

    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    #!/usr/local/bin/python
    #-*- coding:utf-8 -*-

    # import urllib2
    import urllib
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C53445628" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "6f777128a1f8779e6770d751cba73d8e"
    mobile = request.GET.get('phone')    
    # 随机验证码
    code = str(random.randint(10000,99999))
    # 把验证码存入session
    request.session['msgcode'] = code
    text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    req = urllib.request.urlopen(
        url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data= urllib.parse.urlencode(data).encode('utf-8')
    )
    content =req.read()
    res = json.loads(content.decode('utf-8'))
    print(res)
    return HttpResponse(res)


